﻿using System;
using System.ComponentModel;
using System.Threading;

namespace LayeredArchitectureSample.ViewModel
{
    /// <summary>
    /// Raises events in a thread-safe manner
    /// </summary>
    internal static class EventRaiser
    {
        /// <summary>
        /// Raises an event in a thread-safe manner
        /// </summary>
        /// <param name="handler"></param>
        /// <param name="eventSender"></param>
        /// <param name="propertyName"></param>
        public static void RaisePropertyChangedEvent(PropertyChangedEventHandler handler, object eventSender, string propertyName)
        {
            if (eventSender == null) throw new ArgumentNullException("eventSender");
            if (propertyName == null) throw new ArgumentNullException("propertyName");

            PropertyChangedEventHandler eventHandler = Interlocked.CompareExchange(ref handler, null, null);

            if (eventHandler != null)
            {
                eventHandler.Invoke(eventSender, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}